<!--
 * @Author: lijing
 * @e-mail: 1413979079@qq.com
 * @LastEditors: lijing
 * @Date: 2020-06-22 21:53:32
 * @LastEditTime: 2020-07-04 09:12:34
 * @FilePath: \client\src\views\Register.vue
 * @Description: 
--> 
<template>
  <el-card>
    <div slot="header" class="text-center">
      <h3>创建账号</h3>
    </div>
    <el-form
      label-position="left"
      label-width="80px"
      :rules="rules"
      :model="formData"
      ref="registerForm"
    >
      <div class="upload-box">
        <div class="label-text">头像：</div>
        <el-upload
          class="avatar-uploader"
          action="/api/v1/upload"
          :show-file-list="false"
          name="image"
          :limit="1"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :before-upload="beforeAvatarUpload"
        >
          <el-image v-if="formData.url" :src="prefix+formData.url" fit="cover" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="ensure">
        <el-input v-model="formData.ensure" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('registerForm')">提交</el-button>
        <el-button @click="resetForm('registerForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import request from "../http/request";
import Env from "../model/Env";

@Component
export default class Register extends Vue {
  prefix = Env.prefix;
  formData = {
    nickname: "",
    username: "",
    password: "",
    ensure: "",
    url: ""
  };
  validatePass2: Function = (rule: any, value: any, callback: Function) => {
    if (value === "") {
      callback(new Error("请再次输入密码"));
    } else if (value !== this.formData.password) {
      callback(new Error("两次输入密码不一致!"));
    } else {
      callback();
    }
  };
  rules = {
    nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    ensure: [{ required: true, validator: this.validatePass2, trigger: "blur" }]
  };
  submitForm(formName: string) {
    const re: any = this.$refs[formName];
    re.validate((valid: any) => {
      if (valid) {
        request
          .register(this.formData)
          .then(res => {
            if (res.data.code === 0) {
              this.$message({
                showClose: true,
                message: "注册成功",
                type: "success"
              });
              setTimeout(() => {
                this.$router.replace("/login");
              }, 1000);
            } else {
              this.$message({
                showClose: true,
                message: res.data.msg,
                type: "error"
              });
            }
          })
          .catch(() => {
            this.$message({
              showClose: true,
              message: "服务器忙，注册失败",
              type: "error"
            });
          });
      } else {
        this.$message({
          showClose: true,
          message: "请完整填写字段",
          type: "warning"
        });
        return false;
      }
    });
  }
  resetForm(formName: string) {
    const re: any = this.$refs[formName];
    re.resetFields();
  }
  handleAvatarSuccess(res: any, file: any) {
    if (res.code === 0) {
      this.formData.url = res.data;
    } else {
      this.$message({
        showClose: true,
        message: "网络忙，上传失败！",
        type: "error"
      });
    }
  }
  handleAvatarError(res: any, file: any) {
    this.$message({
      showClose: true,
      message: "网络忙，上传失败！",
      type: "error"
    });
  }
  beforeAvatarUpload(file: any) {
    const typeLimit =
      ["image/png", "image/jpeg"].findIndex(ele => ele === file.type) != -1;
    const sizeLimit = file.size / 1024 / 1024 < 20;

    if (!typeLimit) {
      this.$message({
        showClose: true,
        message: "上传的图片只能是 JPG/PNG 格式!",
        type: "error"
      });
    }
    if (!sizeLimit) {
      this.$message({
        showClose: true,
        message: "上传头像图片大小不能超过 2MB!",
        type: "error"
      });
    }
    return typeLimit && sizeLimit;
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin: auto;
  width: 400px;
  margin-top: 20px;
}
.upload-box {
  display: flex;
  justify-content: start;
  margin-bottom: 10px;
  .label-text {
    width: 80px;
  }
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>